package com.css.dzj.dzjfxyj.modules.acquier.service.Impl;

import com.css.dzj.dzjfxyj.common.util.Constant;
import com.css.dzj.dzjfxyj.common.util.R;
import com.css.dzj.dzjfxyj.common.util.ServiceUtil;
import com.css.dzj.dzjfxyj.modules.acquier.entity.JgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.entity.QJgFxyjWarningSignalEntity;
import com.css.dzj.dzjfxyj.modules.acquier.mapper.AcquierMapper;
import com.css.dzj.dzjfxyj.modules.acquier.service.AcquierService;
import com.css.dzj.dzjfxyj.modules.acquier.vo.DistributeInfoVo;
import com.css.dzj.dzjfxyj.modules.acquier.vo.RiskWaringInfoVo;
import com.css.dzj.dzjfxyj.modules.distribute.entity.JgFxyjFenfaEntity;
import com.css.dzj.dzjfxyj.modules.distribute.service.DistributeService;
import com.css.dzj.dzjfxyj.modules.distribute.vo.DistributeVo;
import com.css.dzj.dzjfxyj.modules.reply.entitiy.JgFxyjFeedbackEntity;
import com.css.dzj.dzjfxyj.modules.reply.service.ReplyService;
import com.css.dzj.dzjfxyj.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AcquierServiceImpl implements AcquierService {
    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    private ServiceUtil serviceUtil;
    @Autowired
    private AcquierMapper acquierMapper;
    @Autowired
    private DistributeService distributeService;
    @Autowired
    private ReplyService replyService;

    /**
     * 查看全部(认领)
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<JgFxyjWarningSignalEntity> selectAll(String fxyjDomainId,String fxyjTitle,String fxyjLevel,String fxyjObjectName,
                                                             String startTime1,String endTime1,String startTime,String endTime,Pageable pageable) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = (StringUtils.isEmpty(fxyjDomainId)) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (StringUtils.isEmpty(fxyjTitle)) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (StringUtils.isEmpty(fxyjLevel)) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (StringUtils.isEmpty(fxyjObjectName)) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%" + fxyjObjectName.trim() + "%"));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000s");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTime.between(startDate,endDate));
        }

        if((StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime1 + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime1))&&(!StringUtils.isEmpty(endTime1))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime1 + " 00:00:00.000");
                endDate = sf.parse(endTime1 + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }
        //predicate = ExpressionUtils.and(predicate, q.getState.isNull());
       return jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 查看全部(zh)
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<JgFxyjWarningSignalEntity> selectAllzh(String fxyjDomainId,String fxyjTitle,String fxyjLevel,String fxyjObjectName,
                                                             String dealState,String startTime,String endTime,Pageable pageable) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = (StringUtils.isEmpty(fxyjDomainId)) ? predicate : ExpressionUtils.and(predicate, q.fxyjDomainId.eq(fxyjDomainId.trim()));
        predicate = (StringUtils.isEmpty(fxyjTitle)) ? predicate : ExpressionUtils.and(predicate, q.fxyjTitle.like("%" + fxyjTitle.trim() + "%"));
        predicate = (StringUtils.isEmpty(fxyjLevel)) ? predicate : ExpressionUtils.and(predicate, q.fxyjLevel.eq(fxyjLevel));
        predicate = (StringUtils.isEmpty(fxyjObjectName)) ? predicate : ExpressionUtils.and(predicate, q.fxyjObjectName.like("%" + fxyjObjectName.trim() + "%"));
        if ("0".equals(dealState)){
            predicate = (ExpressionUtils.and(predicate, q.dealState.isNull()));
        }else {
            predicate = (StringUtils.isEmpty(dealState)) ? predicate : ExpressionUtils.and(predicate, q.dealState.eq(dealState));
        }

        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime + " 00:00:00.000");
                endDate = sf.parse(endTime + " 23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.fxyjTransmitTime.between(startDate,endDate));
        }

        return jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 根据id查询
     * @param Id
     * @return
     */
    @Override
    public JgFxyjWarningSignalEntity findById(String Id) {
        QJgFxyjWarningSignalEntity q=QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        return jpaQueryFactory.selectFrom(q).where(q.id.eq(Id)).fetchOne();
    }

    /**
     * 新增
     * @param jgFxyjWarningSignalEntity
     * @param request
     * @return
     */
    @Override
    @Transactional
    public R saveAcquire(JgFxyjWarningSignalEntity jgFxyjWarningSignalEntity, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(jgFxyjWarningSignalEntity)) {
                throw new RuntimeException("新增不能为空");
            }

            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String location = "";
            String address="";
            String orgName = "";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
                address = userInfo.getAddress();
            }
            jgFxyjWarningSignalEntity.setOverState(Constant.DAIOVER);
            jgFxyjWarningSignalEntity.setGetState(Constant.DAIDISTRIBUTE);
            jgFxyjWarningSignalEntity.setRevertState(Constant.DAIOVER);
            jgFxyjWarningSignalEntity.setCreatePreson(suserName);
            jgFxyjWarningSignalEntity.setCreateTime(new Date());
            jgFxyjWarningSignalEntity.setGetTime(new Date());
            acquierMapper.save(jgFxyjWarningSignalEntity);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public void updAcquire(JgFxyjWarningSignalEntity jgFxyjWarningSignalEntity, HttpServletRequest request) {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        jpaQueryFactory.update(q).set(q.overState,Constant.DAIOVER)
                .set(q.dispenseState,Constant.DAIDISTRIBUTE)
                .set(q.revertState,Constant.DAIREPLY)
                .set(q.getState,Constant.YIGET)
                .set(q.operatePerson,jgFxyjWarningSignalEntity.getOperatePerson())
                .set(q.operateOrg,jgFxyjWarningSignalEntity.getOperateOrg())
                .set(q.getTime,jgFxyjWarningSignalEntity.getGetTime())
                .set(q.disposeResult,jgFxyjWarningSignalEntity.getDisposeResult())
                .set(q.disposeExplain,jgFxyjWarningSignalEntity.getDisposeExplain())
                .set(q.dealState,Constant.YIJIESHOU)
                .where(q.id.eq(jgFxyjWarningSignalEntity.getId())).execute();
    }

    /**
     * 修改状态
     * @param id
     */
    @Override
    @Transactional
    public R updState(String id) {
        try {
            if(!"".equals(id) && id!=null){
                QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
                jpaQueryFactory.update(q)
                        .set(q.getState, "1")
                        .where(q.id.eq(id))
                        .execute();
                return R.ok();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public Long getCount() {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        return jpaQueryFactory.select(q.fxyjId.count()).from(q).where(q.dealState.isNull()).fetchOne();
    }

    @Override
    public List<RiskWaringInfoVo> findPushedTasks() {
        QJgFxyjWarningSignalEntity q = QJgFxyjWarningSignalEntity.jgFxyjWarningSignalEntity;
        List<JgFxyjWarningSignalEntity> fxyjWarningSignalEntityList = jpaQueryFactory.selectFrom(q)
                .where(q.dealState.eq("3").or(q.dealState.eq("4")))
                .orderBy(q.createTime.desc())
                .fetch();
        List<RiskWaringInfoVo> riskWaringInfoVoList = new ArrayList<>();
        for(JgFxyjWarningSignalEntity jgFxyjWarningSignalEntity : fxyjWarningSignalEntityList) {
            RiskWaringInfoVo riskWaringInfoVo = new RiskWaringInfoVo();
            riskWaringInfoVo.setWarningSignalEntity(jgFxyjWarningSignalEntity);
            List<DistributeInfoVo> distributeInfoVoList = new ArrayList<>();
            List<JgFxyjFenfaEntity> fenfaEntityList = distributeService.findFenFaInfoByGetId(jgFxyjWarningSignalEntity.getId());
            for (JgFxyjFenfaEntity fenfaEntity : fenfaEntityList) {
                DistributeInfoVo distributeInfoVo = new DistributeInfoVo();
                distributeInfoVo.setJgFxyjFenfaEntity(fenfaEntity);
                if(!StringUtils.isEmpty(fenfaEntity.getId())) {
                    List<JgFxyjFeedbackEntity> feedbackEntityList = replyService.queryByFbId(fenfaEntity.getId());
                    distributeInfoVo.setJgFxyjFeedbackEntityList(feedbackEntityList);
                }
                distributeInfoVoList.add(distributeInfoVo);
            }
            riskWaringInfoVo.setDistributeInfoVoList(distributeInfoVoList);
            riskWaringInfoVoList.add(riskWaringInfoVo);
        }
        return riskWaringInfoVoList;
    }

}
